"""
演示EventBus与HookHub异步事件处理
"""

import asyncio
import threading
import time
from event_bus import EventBus as CPPEventBus
from hook_hub import HookHub


# 记录执行时间和顺序
execution_log = []
log_lock = threading.Lock()


class AsyncEventBusDemo:
    """异步EventBus演示"""
    
    def __init__(self):
        self.cpp_bus = CPPEventBus()
        self.hook_hub = HookHub()
        self._setup_handlers()
        
    def _setup_handlers(self):
        """设置事件处理器"""
        # 注册C++事件处理器
        self.cpp_bus.on(0xC0, self._forward_to_hookhub)
        
        # 注册各种类型的处理器
        self.hook_hub.register("data_event", self.sync_data_handler, priority=100)
        self.hook_hub.register("data_event", self.async_logging_handler, priority=50, is_async=True)
        self.hook_hub.register("data_event", self.async_notification_handler, priority=10, is_async=True)
        
    def _forward_to_hookhub(self, payload: str) -> None:
        """将C++事件转发到HookHub"""
        with log_lock:
            execution_log.append(f"[Forwarder] 接收C++事件: {time.time():.3f}")
        
        # 同步处理
        self.hook_hub.emit("data_event", payload=payload)
        
    def sync_data_handler(self, **kwargs):
        """同步数据处理器"""
        payload = kwargs.get('payload', '')
        with log_lock:
            execution_log.append(f"[SyncHandler] 开始处理: {time.time():.3f}")
        
        # 模拟数据处理
        time.sleep(0.2)
        
        with log_lock:
            execution_log.append(f"[SyncHandler] 处理完成: {time.time():.3f}")
        return f"Processed: {payload}"
        
    async def async_logging_handler(self, **kwargs):
        """异步日志处理器"""
        payload = kwargs.get('payload', '')
        with log_lock:
            execution_log.append(f"[AsyncLogger] 开始记录: {time.time():.3f}")
        
        # 模拟异步日志
        await asyncio.sleep(0.5)
        
        with log_lock:
            execution_log.append(f"[AsyncLogger] 记录完成: {time.time():.3f}")
        return "Logged"
        
    async def async_notification_handler(self, **kwargs):
        """异步通知处理器"""
        payload = kwargs.get('payload', '')
        with log_lock:
            execution_log.append(f"[AsyncNotifier] 开始通知: {time.time():.3f}")
        
        # 模拟异步通知
        await asyncio.sleep(0.8)
        
        with log_lock:
            execution_log.append(f"[AsyncNotifier] 通知完成: {time.time():.3f}")
        return "Notified"
        
    def send_event(self, data: str):
        """发送事件"""
        self.cpp_bus.emit(0xC0, data)
        
    async def send_async_event(self, data: str):
        """异步发送事件"""
        loop = asyncio.get_event_loop()
        await loop.run_in_executor(None, self.cpp_bus.emit, 0xC0, data)
        
    def shutdown(self):
        """关闭"""
        self.cpp_bus.shutdown()


async def demonstrate_async_processing():
    """演示异步处理"""
    print("=== EventBus与HookHub异步处理演示 ===")
    
    demo = AsyncEventBusDemo()
    
    # 清空日志
    execution_log.clear()
    
    print("发送第一个事件...")
    start_time = time.time()
    
    # 发送事件
    demo.send_event("event_data_1")
    
    # 等待一小段时间再发送第二个事件
    await asyncio.sleep(0.1)
    print("发送第二个事件...")
    demo.send_event("event_data_2")
    
    # 等待所有处理完成
    await asyncio.sleep(2)
    
    end_time = time.time()
    
    print(f"\n总耗时: {end_time - start_time:.3f}秒")
    
    print("\n执行日志:")
    for log in execution_log:
        print(log)
    
    # 分析并发处理
    print("\n=== 并发处理分析 ===")
    analyze_concurrent_processing()
    
    demo.shutdown()


def analyze_concurrent_processing():
    """分析并发处理"""
    sync_handlers = [log for log in execution_log if "SyncHandler" in log]
    async_loggers = [log for log in execution_log if "AsyncLogger" in log]
    async_notifiers = [log for log in execution_log if "AsyncNotifier" in log]
    
    print(f"同步处理器调用: {len(sync_handlers)} 次")
    print(f"异步日志处理器调用: {len(async_loggers)} 次")
    print(f"异步通知处理器调用: {len(async_notifiers)} 次")
    
    # 检查是否并发执行
    concurrent_indicators = []
    
    # 查找异步任务是否与同步任务重叠
    for log in execution_log:
        if "开始" in log:
            concurrent_indicators.append(("start", log))
        elif "完成" in log:
            concurrent_indicators.append(("end", log))
    
    print(f"\n并发执行特征:")
    print("1. 同步处理器按顺序执行（阻塞）")
    print("2. 异步处理器可以并发执行（非阻塞）")
    print("3. 多个事件可以被同时处理")
    print("4. 异步任务在后台运行，不影响主线程")


async def main():
    """主函数"""
    await demonstrate_async_processing()


if __name__ == "__main__":
    asyncio.run(main())